<template>
    <div class="content-wrapper">
        <el-row class="content-row">
            <el-col class="height-init cityTree" :span="3">
                <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
            </el-col>
            <el-col class="height-init" :span="21">
                <div class="container">
                    <el-row class="handle-box">
                        <el-input v-model="query.name" placeholder="报名人姓名" class="handle-input mr10"></el-input>
                        <el-input v-model="query.telphone" placeholder="手机号" class="handle-input mr10"></el-input>
                        <el-date-picker
                                v-model="query.time"
                                type="datetimerange"
                                range-separator="至"
                                @change="dateChange"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                :default-time="['00:00:00', '23:59:59']">
                        </el-date-picker>

                        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                        <el-button type="primary" icon="el-icon-plus" class="handle-del" @click="reSetForm">重置
                        </el-button>

                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <div style="float: left;text-align: left">
                                <div style="height: 25px;"> 活动名称：{{title}}</div>
                                <div style="height: 25px;">报名人数：{{applyNum}}</div>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row class="list-table-row">
                        <el-table
                                :data="tableData"
                                border
                                class="table"
                                ref="multipleTable"
                                height="100%"
                                header-cell-class-name="table-header"
                                @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" width="55" align="center"></el-table-column>
                            <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
                            <el-table-column prop="name" label="报名人" show-overflow-tooltip/>
                            <el-table-column prop="telphone" label="手机号" show-overflow-tooltip/>
                            <el-table-column prop="cityName" label="所在城市" show-overflow-tooltip/>
                            <el-table-column prop="num" label="人数" show-overflow-tooltip/>
                            <el-table-column prop="fee" label="费用" show-overflow-tooltip/>
                            <el-table-column prop="dataource" label="来源" show-overflow-tooltip/>
                            <el-table-column prop="applyTime" label="报名时间" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    {{renderTimeWithOutYear(scope.row.applyTime)}}
                                </template>
                            </el-table-column>

                            <el-table-column label="操作" width="140" align="center">
                                <template slot-scope="scope">
                                    <el-button v-if="scope.row.status == 0 " type="text" size="small"
                                               @click="updateStatus(scope.row,1)">确认报名
                                    </el-button>
                                    <el-button v-if="scope.row.status == 1 " type="text" size="small"
                                               @click="updateStatus(scope.row,0)">取消报名
                                    </el-button>

                                    <el-button type="text" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-row>
                    <el-row class="pagination-self">
                        <el-pagination
                                background
                                layout="total, sizes, prev, pager, next"
                                :current-page="query.pageNo"
                                :page-size="query.pageSize"
                                :total="pageTotal"
                                @size-change="handleSizeChange"
                                @current-change="handlePageChange"
                        ></el-pagination>
                    </el-row>
                </div>
            </el-col>
        </el-row>


        <el-dialog
                :title="dialogTitle"
                width="30%"
                :closeOnClickModal='false'
                :visible.sync="dialogFormVisible">
            <el-form  :model="ruleForm" ref="ruleForm" :rules="rules" label-width="140px" >
                <el-form-item label="报名人" prop="name" >
                    <el-input v-model='ruleForm.name'/>
                </el-form-item>
                <el-form-item label="电话" prop="telphone" >
                    <el-input v-model='ruleForm.telphone' />
                </el-form-item>
                <el-form-item label="人数" prop="num" >
<!--                    <el-input-numbe v-model='ruleForm.num' type="number" min="1" :max="maxPeopleApplyNum" />-->
                    <el-input-number v-model="ruleForm.num" controls-position="right" @change="handleChange" :min="1" :max="maxPeopleApplyNum"></el-input-number>

                </el-form-item>

                <el-form-item :key="item.id" v-for="item in externalColumn" :label="item.name" :prop="'externalInfo.'+item.code" >
                    <el-input v-model="ruleForm.externalInfo[item.code]" :placeholder="item.placeholder" />
                </el-form-item>

            </el-form>
            <div slot="footer" >
                <el-button type="primary" @click="changeApplyUserInfo" >确定修改</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    // import { fetchList, updateAdvertise } from '../../../../api/advertise'
    // import { getMoreSpace } from '../../../../api/advertiseSpace'
    import {getCityTree} from '../../../api/city'
    import {
        deleteActivity,
        getPage,
        updateStatus,
        getActivityInfo,
        getApplyInfoList,
        updateApplyStatus,
        getExternalByActivityId,
        updateActivityApply
    } from '../../../api/activity/activity'


    export default {
        name: 'activityList',
        data() {
            return {
                activityObj:{},
                title: '',
                applyNum: '',
                maxPeopleApplyNum:'',
                activityStatusOptions: [{
                    value: '0',
                    label: '草稿'
                }, {
                    value: '1',
                    label: '未开始'
                }, {
                    value: '2',
                    label: '报名中'
                }, {
                    value: '3',
                    label: '活动待开始'
                }, {
                    value: '4',
                    label: '活动中'
                }, {
                    value: '5',
                    label: '已结束'
                }, {
                    value: '6',
                    label: '已失效'
                }],
                query: {
                    pageNo: 1,
                    pageSize: 20,
                    cityCode: '',
                },
                dialogTitle: '报名信息编辑',
                dialogFormVisible: false,
                externalColumn:[],
                rules: {
                    name:[
                        { required: true, message: '报名人不能为空', trigger: 'blur'}
                    ],
                    telphone:[
                        { required: true, message: '电话不能为空', trigger: 'blur'}

                    ],
                    // num:[
                    //     { required: true, min:1, max:12, message: '人数不能为空', trigger: 'blur'}
                    //     ,{ validator : this.validateApplyNum, trigger: 'blur'}
                    //
                    // ],
                    externalInfo:{}
                },

                tableData: [],
                multipleSelection: [],
                pageTotal: 0,
                spaces: [],
                statusOptions: [{
                    value: '0',
                    label: '草稿'
                }, {
                    value: '2',
                    label: '已下架'
                }, {
                    value: '3',
                    label: '上架中'
                }, {
                    value: '4',
                    label: '等待上架'
                }, {
                    value: '5',
                    label: '已结束'
                }],ruleForm:{
                    externalInfo: {}
                    ,id: ''
                    ,name: ""
                    ,num: ''
                    ,telphone: ""
                },
                data: [],
                defaultProps: {
                    children: 'children',
                    label: 'name',
                    isLeaf: 'leaf'
                }
            };
        },
        activated() {

            this.getData();
            // this.getMoreSpace();
            this.getCityTree();
        },
        created() {
            //this.getData();
            // this.getMoreSpace();
            this.getCityTree();
            this.loadActivityInfo();
        },
        methods: {
            reSetForm(){
                this.query={};
                this.query.pageNo=1;
                this.query.pageSize =20;
                this.query.cityCode= ''
                this.getData();
            }, changeApplyUserInfo(){
                let that = this;
                console.log('changeApplyUserInfo====>',that.ruleForm,that.activityObj,that.rules);
                that.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        let externalInfo = JSON.stringify(that.ruleForm.externalInfo);
                        that.ruleForm.externalInfo = externalInfo;

                        updateActivityApply(that.ruleForm).then(res => {
                            if (res.code == '0') {
                                this.fullscreenLoading = false;
                                this.$message({
                                    message: '修改成功',
                                    type: 'success'
                                });
                                this.dialogFormVisible = false;
                                let info = res.data;
                                this.applyNum = info.applyNum;

                                this.getData();
                            } else {
                                this.fullscreenLoading = false;
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                            }
                        });

                    } else {
                        return false;
                    }
                });
            },
            loadActivityInfo() {
                let self = this;

                let path = this.$route.fullPath.split("/");

                let id = path[path.length - 1];

                getActivityInfo(id).then(res => {
                    if (res.code === '0') {
                        let info = res.data.activityManagement;
                        this.title = info.title;
                        this.applyNum = info.applyNum;
                        this.maxPeopleApplyNum = info.maxPeopleApplyNum;
                    }
                })
                this.query.activityId = id;
                getApplyInfoList(this.query).then(res => {
                    this.tableData = res.data.records;
                    this.pageTotal = res.data.total || 50;
                });

                getExternalByActivityId({activityId: id}).then(res => {
                    if (res.code == '0') {
                        this.externalColumn = res.data;
                        if(this.externalColumn){
                            this.externalColumn.forEach(element => {
                                console.log("externalColumn====>",element);
                                if(element.required === 1){
                                    this.rules.externalInfo[element.code] = [{ required: true, message: element.placeholder, trigger: 'blur'}];
                                }
                            });
                        }

                    }
                });
            },
            //修改报名状态
            updateStatus(row, status) {
                // 二次确认下架
                let alertContent = "确定取消报名吗";
                let alertSuccContent = "取消报名成功";

                if (status == 1) {
                    alertContent = "确定报名吗";
                    alertSuccContent = "报名成功";

                }
                this.$confirm(alertContent, '提示', {
                    type: 'warning'
                }).then(() => {
                    updateApplyStatus({id: row.id, status: status, operation: 'obtained'}).then(res => {
                        if (res.code == '0') {
                            this.$message.success(alertSuccContent);
                            this.getData();

                            if (status == 1) {
                                this.applyNum = this.applyNum + row.num;
                            } else {
                                this.applyNum = this.applyNum - row.num;

                            }
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                }).catch(() => {
                });
            },
            /**
             * 获取城市树
             */
            getCityTree() {
                console.log("--->进来了获取城市树")
                getCityTree().then(res => {
                    console.log(res.data);
                    this.data = res.data;
                })
            },
            /**
             * 获取坑位
             */
            // getMoreSpace(){
            //     getMoreSpace({type:1,category:1}).then(res=>{
            //         this.spaces = res.data;
            //     })
            // },
            /**
             * 点击树
             */
            handleNodeClick(data) {
                this.query.cityCode = data.code;
                this.getData();
            },
            /**
             * 获取列表
             */
            getData() {
                getApplyInfoList(this.query).then(res => {
                    this.tableData = res.data.records;
                    this.pageTotal = res.data.total || 50;
                });
            },
            /**
             * 新增活动
             */
            addActity() {
                this.addTag('福利活动添加', '/activity/add', 'advertiseAdd')
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageNo', 1);
                this.getData();
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    deleteActivity({id: row.id, operation: 'deleted'}).then(res => {
                        if (res.code == '0') {
                            this.$message.success('删除成功');
                            this.getData();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                }).catch(() => {
                });
            },
            //下架操作
            handleDown(index, row) {
                // 二次确认下架
                this.$confirm('确定要下架吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    updateStatus({id: row.id, status: 2, operation: 'obtained'}).then(res => {
                        if (res.code == '0') {
                            this.$message.success('下架成功');
                            this.getData();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                }).catch(() => {
                });
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 编辑操作
            showEditDialog(row) {

                console.log(this.externalColumn);
                let that = this;
                that.ruleForm = JSON.parse(JSON.stringify(row));
                that.dialogFormVisible = !that.dialogFormVisible;
                if (that.ruleForm.externalInfo) {
                    that.ruleForm.externalInfo = JSON.parse(that.ruleForm.externalInfo)
                } else {
                    that.ruleForm.externalInfo = {}
                }
            },
            // 编辑操作
            handleApply(index, row) {
                this.addTag('福利活动报名详情', '/activity/edit/' + row.id, 'activityEdit');
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageNo', val);
                this.getData();
            },
            handleSizeChange(val) {
                this.$set(this.query, 'pageSize', val);
                this.getData();
            }, dateChange(val) {
                if (val != null && val !== undefined && val.length > 0) {
                    this.query.startTime = new Date(val[0]).getTime();
                    this.query.endTime = new Date(new Date(val[1]).setHours(23, 59, 59)).getTime();
                } else {
                    this.query.startTime = null;
                    this.query.endTime = null;
                }
            }
        }
    };
</script>

<style scoped>

    .content-wrapper {
        height: 100%;
        overflow-y: hidden;
    }

    .content-row {
        height: 100%;
    }

    .cityTree {
        overflow-y: scroll;
    }

    .height-init {
        height: 100%;
    }

    .container {
        height: 100%;
    }

    .handle-box {
        height: 6.5%;
    }

    .handle-input {
        width: 120px;
        display: inline-block;
    }

    .list-table-row {
        height: 83%;
    }

    .table {
        width: 100%;
        height: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

    .pagination-self {
        height: 10%;
        text-align: right;
        margin-top: 5px;
    }
</style>
